<template>
	<uni-popup ref="popup" type="bottom" :mask-click="!isInner">
		<view v-if="data" class="p-16" style="border-radius:12px 12px 0 0;background:#FFF;">
			<view class="flex">
				<image class="radius-8 mr-12 flex-shrink" mode="aspectFill" style="width:88px;height:88px;"
					:src="coverPicture"></image>
				<text class="fs-14 text-color-regular font-semibold overflow-hidden flex-1 w-0"
					style="text-overflow:ellipsis;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:5;">{{
						data.activeTitle }}</text>
			</view>
			<view class="mt-16 flex justify-between">
				<view class="flex-col">
					<view class="mb-4 fs-16">
						<text class="color-primary font-semibold">¥{{ numberFormat(data.activeGroupBuy.groupBuyPrice)
							}}</text>
						<text class="text-color-hint">/份</text>
					</view>
					<view class="text-color-hint fs-12">剩余{{ data.remainStock }}份<text v-if="isLimitBuy">，最多可买{{
						limitBuyNum }}份</text></view>
				</view>
				<number-input-box :min="1" :value="formData.orderNum" :max="limitBuyNum" :disabled="disableOrder || data.activeGroupBuy.freeType!==0"
					@change="onNumberChange"></number-input-box>
			</view>
			<template v-if="isSignUp && formData.activeEnrollInfos && formData.activeEnrollInfos.length && !isZeroGroupBuy">
				<view class="h-16 bg-default mt-16" style="margin-left:-16px;margin-right:-16px;"></view>
				<view class="pt-16 pb-4">
					<view class="fs-16 text-bold">报名信息</view>
					<view class="pl-12 overflow-auto" style="max-height:30vh;">
						<template v-for="(item, i) in formData.activeEnrollInfos" :key="i">
							<view v-if="item.type === 1" class="flex item-center mt-16" :key="`${item.type}-${i}`">
								<text class="flex-shrink fs-16">{{ item.title }}：</text>
								<input v-model="item.content" class="fs-12 h-27 px-8 radius-4"
									:placeholder="`请输入${item.title}`" placeholder-class="text-color-hint" />
							</view>
							<view v-if="item.type === 2" class="flex flex-wrap mt-16" :key="`${item.type}-${i}`">
								<text class="flex-shrink w-full fs-16 mb-8">{{ item.title }}：</text>
								<view class="flex flex-wrap">
									<!-- <view v-for="(option, j) in item.activeEnrollInfoOptions" :key="j"
										class="flex item-center mr-20"
										@click="onRadioChange(option, item.activeEnrollInfoOptions, item.type)">
										<image v-if="option.checkState === 2" class="size-16 mr-8"
											src="@/static/svg/radio-checked.svg"></image>
										<image v-else class="size-16 mr-8"
											src="@/static/svg/activity/icon-radio-default.svg"></image>
										<text class="fs-12 text-color-hint">{{ option.optionText }}</text>
									</view> -->
									<view v-for="(option, j) in item.activeEnrollInfoOptions" :key="j"
										class="mx-4 px-12 py-4 my-2 radius-8 bg-default-c"
										:class="{ 'bg-primary': option.checkState === 2, 'text-white': option.checkState === 2 }"
										@click="onRadioChange(option, item.activeEnrollInfoOptions, item.type)">
										<text class="fs-12">{{ option.optionText }}</text>
									</view>
								</view>
							</view>
							<view v-if="item.type === 3" class="flex flex-wrap mt-16" :key="`${item.type}-${i}`">
								<text class="flex-shrink w-full fs-16 mb-8">{{ item.title }}：</text>
								<view class="flex flex-wrap">
									<!-- <view v-for="(option,j) in item.activeEnrollInfoOptions" :key="j" class="flex item-center mr-20" @click="onRadioChange(option, item.activeEnrollInfoOptions,item.type)">
										<image v-if="option.checkState===2" class="size-16 mr-8" src="@/static/svg/checkbox-red-checked.svg"></image>
										<image v-else class="size-16 mr-8" src="@/static/svg/checkbox-default.svg"></image>
										<text class="fs-12 text-color-hint">{{option.optionText}}</text>
									</view> -->
									<view v-for="(option, j) in item.activeEnrollInfoOptions" :key="j"
										class="mx-4 px-12 py-4 my-2 radius-8 bg-default-c"
										:class="{ 'bg-primary': option.checkState === 2, 'text-white': option.checkState === 2 }"
										@click="onRadioChange(option, item.activeEnrollInfoOptions, item.type)">
										<text class="fs-12">{{ option.optionText }}</text>
									</view>
								</view>
							</view>
						</template>
					</view>
				</view>
			</template>
			<view v-if="discount" class="mt-12 flex justify-between item-center">
				<text class="fs-16 text-color-regular font-semibold">优惠</text>
				<view class="flex item-center leading-22">
					<text class="fs-14 text-color-regular font-normal mr-24">{{ `满${discount.num}件${discount.discount}折`
						}}</text>
					<text class="color-primary fs-14">-¥</text>
					<text class="color-primary fs-16 font-semibold">{{ numberFormat(discountAmt) }}</text>
				</view>
			</view>
			<view class="mt-12 flex justify-between item-center" @click="showCounp(true)">
				<text class="fs-16 text-color-regular font-semibold">优惠券</text>
				<view class="flex item-center justify-between">
					<view class="flex item-center" v-if="currentCoupon">
						<text class="fs-14 text-color-regular font-normal mr-24">{{ currentCoupon.title }}</text>
						<text class="color-primary fs-14">-¥</text>
						<text class="color-primary fs-16 font-semibold">{{ currentCoupon.amt }}</text>
					</view>
					<image class="w-16 h-17 ml-4" src="@/static/svg/icon-arrow-right.svg"></image>
				</view>
			</view>
			<view class="h-1 mt-16 mb-12" style="background-color:#F7F7F7;"></view>
			<view class="flex justify-between item-center">
				<view>
					<text class="fs-16 text-color-regular font-semibold">总计：</text>
					<text class="fs-24 color-primary font-semibold">¥{{ isZeroGroupBuy ? 0 : toPayAmt }}</text>
				</view>
				<view class="flex center bg-primary radius-8 px-40 h-46 text-white fs-16"
					:style="disableOrder ? 'background:#999' : ''" @click="toPay">
					{{ '立即支付' }}
				</view>
			</view>
		</view>
		<uni-popup ref="counpPopup" type="bottom" :mask-click="false">
			<view class="uni-bg-white fs-14">
				<view class="flex justify-between item-center h-40" style="border-bottom:1px solid #f5f5f5;">
					<text class="text-color-hint p-10" @click="showCounp(false)">收起</text>
					<text class="color-secondary-info p-10" @click="counpConfirm">确定</text>
				</view>
				<view class="fs-20 font-bold text-center mb-16">选择优惠券</view>
				<view class="p-16" style="max-height: 50vh;overflow: auto;" v-if="couponList && couponList.length">
					<view v-for="(item, i) in couponList" :key="i"
						class="coupon-item flex justify-between item-center px-16 py-8 mb-16"
						:class="isUseCoupon(item) ? 'active' : ''" @click="clickCoupon(item, i)">
						<view class="left flex-col" :class="isUseCoupon(item) ? 'color-primary' : 'text-color-hint'">
							<view class="fs-40 text-center"><text class="fs-16">¥</text>{{ item.amt }}</view>
							<view class="fs-12 text-center"
								:style="isUseCoupon(item) ? 'color: rgba(250,69,67,0.6);' : ''">{{
									item.fullAmount == 0 ? `无门槛券` : `满${item.fullAmount}元可用` }}</view>
						</view>
						<view class="right ml-24 flex item-center justify-between">
							<view class="flex-col fs-12 text-color-hint justify-between">
								<view class="fs-16 font-bold c3 mb-16 mt-4">{{ item.title }}</view>
								<view>{{ item.receiveTime }}-{{ item.expireTime }}</view>
							</view>
							<image v-if="checkIndex === i" class="size-16 ml-12" src="@/static/svg/radio-checked.svg">
							</image>
							<image v-else class="size-16 ml-12" src="@/static/svg/radio-default.svg"></image>
						</view>
					</view>
				</view>
				<view class="flex-col item-center justify-center py-16" v-else>
					<image style="width:60px;height:60px;" src="@/static/svg/order/empty-order.svg"></image>
					<view class="mt-4 text-center fs-12 text-color-regular font-normal leading-17">暂无优惠券</view>
				</view>
			</view>
		</uni-popup>
	</uni-popup>
</template>

<script setup>
import { computed, onMounted, ref, unref, watchEffect } from 'vue'
import {
	createGroupBuyOrder,
	createZeroGroupBuyOrder,
	orderPayApi,
	getActiveOrderNumApi,
	queryOrderPay,
	getRedAvailableStatusApi
} from '@/api/order.js'
import { availableRedPacketListApi } from '@/api/activity.js'
import { useActivity } from '@/hooks/useActivity.js'
import { numberFormat, floorNumber } from '@/utils/index.js'

const props = defineProps({
	data: {
		type: Object,
		required: true
	},
	// 活动分享码
	code: {
		type: String,
		default: ''
	},
	groupBuyOrderId: {
		type: String,
		default: ''
	},
	isZeroGroupBuy: {
		type: Boolean,
		default: false
	},
	extParams: {
		type: Object,
	},
})

const emits = defineEmits(['toPay'])

const { isSignUp, coverPicture } = useActivity(props.data)

const couponList = ref([])

const checkIndex = ref('')

const currentCoupon = ref(null)

const getCouponList = () => {
	availableRedPacketListApi({ id: props.data.id }).then(res => {
		couponList.value = res
	})
}

const clickCoupon = (item, index) => {
	if (isUseCoupon(item)) {
		if (index === checkIndex.value) {
			checkIndex.value = ''
		} else {
			checkIndex.value = index
		}
	}
}

const counpConfirm = () => {
	if (checkIndex.value || checkIndex.value === 0) {
		currentCoupon.value = couponList.value[checkIndex.value]
	} else {
		currentCoupon.value = null
	}
	showCounp(false)
}

// 是否可以使用优惠券
const isUseCoupon = (item) => {
	if (item.fullAmount !== 0) {
		return item.fullAmount <= (props.data.activePrice * formData.value.orderNum - discountAmt.value)
	}
	return true
}

const onNumberChange = (val) => {
	formData.value.orderNum = val
}

const onRadioChange = (option, options, type) => {
	if (type == 2) {
		if (option.checkState === 2) {
			option.checkState = 1
		} else {
			options.map(op => op.checkState = 1)
			option.checkState = 2
		}
	} else {
		option.checkState = option.checkState == 2 ? 1 : 2
	}

}

const hasBuyNum = ref(0)
const getActiveOrderNum = () => {
	if (!isLimitBuy.value) return // 不限购，不需要调用接口查询已购数量
	getActiveOrderNumApi({
		activeId: props.data.id
	}).then(res => {
		hasBuyNum.value = res
	})
}

// 是否可以使用红包
const canUseRedPacket = ref(false)
const getRedAvailableStatus = () => {
	if (!props.data.activeRedPacket) return
	getRedAvailableStatusApi({ activeId: props.data.id }).then(res => {
		canUseRedPacket.value = res
	})
}

// 是否有优惠，多件多折
const discount = computed(() => {
	if (props.data.activeDiscount && props.data.activeDiscount.length > 0) {
		let maxDiscount
		for (let i = 0; i < props.data.activeDiscount.length; i++) {
			const item = props.data.activeDiscount[i]
			if (formData.value.orderNum >= item.num) {
				if (!maxDiscount) {
					maxDiscount = item
				} else if (maxDiscount.num < item.num) {
					maxDiscount = item
				}
			}
		}
		return maxDiscount
	}
	return null
})

// 优惠金额
const discountAmt = computed(() => {
	if (discount.value) {
		return +floorNumber(props.data.activePrice * formData.value.orderNum * (10 - discount.value.discount) / 10)
	}
	return 0
})

// 是否限购，limitBuyNum为空不限购;报名活动，limitEnrollNum为空不限购
const isLimitBuy = computed(() => {
	return isSignUp.value ? +props.data.limitEnrollNum > 0 : +props.data.limitBuyNum > 0
})

// 最多可买 = 限购数量 - 已购数量；不限购则为剩余库存
// 最多可买不能超过剩余库存
const limitBuyNum = computed(() => {
	return isLimitBuy.value ? Math.min((isSignUp.value ? props.data.limitEnrollNum : props.data.limitBuyNum) - hasBuyNum.value, props.data.remainStock) : props.data.remainStock
})

// 不可下单
const disableOrder = computed(() => {
	return isLimitBuy.value && limitBuyNum.value <= 0
})

const toPayAmt = computed(() => {
	let price = props.data.activeGroupBuy.groupBuyPrice * formData.value.orderNum - discountAmt.value - (currentCoupon.value && currentCoupon.value.amt ? currentCoupon.value.amt : 0)
	return numberFormat(price > 0 ? price : 0)
})

const formData = ref({
	activeEnrollInfos: [], // 报名信息列表
	activeId: props.data.id, // 活动id
	code: '', // 活动分享码
	orderNum: 1, // 下单数量
	redPacketBillId: '', // 红包id
	userId: ''
})

watchEffect(() => {
	formData.value.activeEnrollInfos = props.data.activeEnrollInfos || []
	formData.value.code = props.code || ''
})

const showToast = (title) => {
	uni.showToast({
		title,
		icon: 'none'
	})
}
const checkEnrollInfoType1 = (info) => {
	if (info.mustState === 2 && !info.content?.trim()) {
		showToast(`${info.title}：请输入内容！`)
		return false;
	}
	return true;
}
const checkEnrollInfoType2 = (info) => {
	if (info.mustState === 2 && info.activeEnrollInfoOptions.every(item => item.checkState === 1)) {
		showToast(`${info.title}：请选择一个选项！`)
		return false;
	}
	return true;
}
const checkEnrollInfoType3 = (info) => {
	if (info.mustState === 2 && info.activeEnrollInfoOptions.every(item => item.checkState === 1)) {
		showToast(`${info.title}：请至少选择一个选项！`)
		return false;
	}
	return true;
}

const checkInput = () => {
	if (isSignUp.value && formData.value.activeEnrollInfos?.length && !props.isZeroGroupBuy) {
		return formData.value.activeEnrollInfos.every(item => {
			if (item.type === 1) return checkEnrollInfoType1(item);
			if (item.type === 2) return checkEnrollInfoType2(item);
			return checkEnrollInfoType3(item);
		});
	}
	return true;
};

const toPay = () => {
	if (!checkInput()) return;

	if (disableOrder.value) return
	// 使用红包
	if (currentCoupon.value) {
		formData.value.redPacketBillId = currentCoupon.value.id
	}
	if (props.groupBuyOrderId) {
		formData.value.groupBuyOrderId = props.groupBuyOrderId
	}
	if (props.extParams) {
		formData.value = {
			...formData.value,
			...(props.extParams || {})
		};
	}
	if (props.isZeroGroupBuy) {
		createZeroGroupBuyOrder(unref(formData)).then(res => {
			uni.navigateTo({
				url: `/pagesA/order/group-buy-detail?groupBuyOrderItemId=${res}&activeId=${props.data.id}`,
				success: (res) => {
				}
			})
			onClose()
		});
		return;
	}
	uni.showLoading();
	createGroupBuyOrder(unref(formData)).then(res => {
		if (res.orderNo) {
			if (res.zeroState != 2) {
				waitPay(res.orderNo, res.orderId)
			} else {
				queryOrderPay({ orderNo: res.orderNo }).then((res) => {
					console.log('查单结果', res)
				}).finally(() => {
					uni.hideLoading()
					uni.navigateTo({
						url: '/pages/home/home?tab=1',
						success: (res) => {
							if (isSignUp.value) {
								uni.$emit('signUpSuccess', {
									orderId: res.orderId,
									orderNo: res.orderNo
								})
							}
						}
					})
					onClose()
				})
			}
		}
	}).finally(uni.hideLoading)
}

const waitPay = async (orderNo, orderId) => {
	const res = await orderPayApi({ orderNo })
	const orderInfo = JSON.parse(res.orderNo)
	uni.requestPayment({
		provider: 'wxpay',
		...orderInfo,
		success() {
			console.log({ orderNo, orderId })
			uni.showLoading()
			queryOrderPay({ orderNo }).then((res) => {
				console.log('查单结果', res)
			}).finally(() => {
				uni.hideLoading()
				uni.navigateTo({
					url: `/pagesA/order/group-buy-detail?id=${orderId}&activeId=${props.data.id}`,
					success: (res) => {
						if (isSignUp.value) {
							uni.$emit('signUpSuccess', {
								orderId,
								orderNo
							})
						}
					}
				})
				onClose()
			})
		},
		fail(e) {
			if (e.errMsg === 'requestPayment:fail cancel') {
				// 取消支付
				queryOrderPay({ orderNo }).then((res) => {
					console.log('查单结果', res)
				}).finally(() => {
					uni.navigateTo({
						url: `/pagesA/order/wait-pay?orderNo=${orderNo}&id=${orderId}`
					})
					onClose()
				})
			} else {
				uni.showToast({
					icon: 'none',
					title: e.errMsg,
					duration: 2000
				})
			}
		}
	})
}

const popup = ref(null)
const counpPopup = ref(null)
const isInner = ref(false)

const onClose = () => {
	popup.value && popup.value.close()
}
const showCounp = (value) => {
	if (value) {
		isInner.value = true
		counpPopup.value && counpPopup.value.open()
	} else {
		isInner.value = false
		counpPopup.value && counpPopup.value.close()
	}
}

const show = async (value, detail) => {
	if (value) {
		getActiveOrderNum()
		getRedAvailableStatus()
		getCouponList()
		popup.value && popup.value.open()
	} else {
		popup.value && popup.value.close()
	}
}

defineExpose({
	show
})
</script>
<style scoped lang="scss">
.coupon-item {
	background-image: url("https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/bg-notes-grey.png");
	background-repeat: no-repeat;
	background-size: 100% 100%;

	&.active {
		background-image: url("https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/bg-notes-active.png");
	}

	.left {
		width: 72px;
	}

	.right {
		width: 255px;
	}
}
</style>